<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Transformers\UserTransformer;
use App\Models\PayUsers;
use App\Services\Mqtt\Publishs;
use App\Services\Mqtt\Subscribes;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

require_once 'Ali/AopClient.php';
require_once 'Ali/AlipaySystemOauthTokenRequest.php';
class UserController extends Controller
{
    public function __construct()
    {

    }

    public function users(Request $request)
    {
        $source = $request->source; // 1.微信 2.支付宝
        $code = $request->code;
        $user = [];
        if ($code) {
            if (1 == $source) {
                $user = $this->wxAccessToken($code);
                if (!empty($user) && array_key_exists('openid', $user)) {
                    $openid = $user['openid'];
                    $isHave = DB::table('pay_users')->where('openid', $openid)->first();
                    if (!$isHave) {
                        $data = array(
                            'openid' => $openid,
                            'created_at' => date('Y-m-d H:i:s', time())
                        );
                        $userId = DB::table('pay_users')->insertGetId($data);
                        $user['userId'] = $userId;
                    } else {
                        $user['userId'] = $isHave->id;
                    }

                }
                return $this->success($user);
            }
            if (2 == $source) {
                $user = $this->aliAccessToken($code);
                if($user &&  array_key_exists('alipay_system_oauth_token_response', $user)){
                    $openid = $user['alipay_system_oauth_token_response']['user_id'];
                    $aliuser['openid'] = $openid;

                    $isHave = DB::table('pay_users')->where('openid', $openid)->first();
                    if (!$isHave) {
                        $data = array(
                            'openid' => $openid,
                            'created_at' => date('Y-m-d H:i:s', time())
                        );
                        $userId = DB::table('pay_users')->insertGetId($data);
                        $aliuser['userId'] = $userId;
                    } else {
                        $aliuser['userId'] = $isHave->id;
                    }
                }
                return $this->success($aliuser);
            }
        }
        return $this->success($user);
    }

    public function wxAccessToken($code)
    {
        $appid = 'wx47edb2ad95cd8fbe';
        $secret = 'd0e2b909e7806833bade8182d7f56bf4';
        $grant_type = 'authorization_code';
        $data = [];
        if ($code) {
            $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=';
            $url .= $appid;
            $url .= '&secret=';
            $url .= $secret;
            $url .= '&code=';
            $url .= $code;
            $url .= '&grant_type=';
            $url .= $grant_type;
            $accessToken = $this->curl_get($url);
            $data = json_decode($accessToken, 1);
        }
        return $data;

    }


    public function aliAccessToken($code)
    {
        $aop = new \AopClient();
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = '2021001193602759';
        $aop->rsaPrivateKey = 'MIIEowIBAAKCAQEAljhBJgEvsYkjEIVEuYzAVPxWkWA0rk8nWChtTMr3l2ScjbWrlV6C39AQ56kxmR+W+nmthP7+BvfRCqD1oWfR+J+ZXG2t077L7qfREsZGiI3T93dEXcmFlMp8QSzyPz6FdpI2UFvu8gT3ROjLhT32HzfQ5waBzSH58gJCNSu5/Fc7H1bo+pQF6QcJUsMd6FdbHNzrh1PxOoRtMUgASqLLA+dc8zWApMehhlftXLBG3npxavDp4xE2EwtOBDhdKuwjsi6TYm3zxI4gEn2bihjj0kplzLrJ6QGcbKVXZLNL9SMrzRuHF5eq7SXY4tnW6pkdr0yKochGkNf7+QW5MgwZCQIDAQABAoIBAAv5X/gPkCWusMTYWqoPtiUQGDZuXMSoOpKkZlIAu8utkW0aVhsJ9ZSxmSdeLT3vbrF4kYRQbx9PEbKvMeUzyWDwF+FuPLTsOIVFizzb4TNxWrwXHbP8JFG/8jefxY+VBD53WSz+pwVTsAImLFLqpXvHjzdbJW2cj7fixjRG0AR1ME9otwZOy2klPXj/EtW+5iOiNZIKI7P4LIno6cfxgjWl8LXW3CiECpyNLfy5vk2sJQyQAcowEMToW5ITyYfj+LxYH92Yre6xbmJGn6roACnNug3TWSgKnlJg4gxYGiHlzQKTTOhuVNQYoFMEbUYAWh+zNg7N3RnxvCnnr998BoECgYEAzB8+98EbQZLNLzaHRjMeIVK2D2mGMSGeJiQWQL1wYyY9ULEz4xkDDSnxX0gfPHQfw4UOZnm+ud9P3M9A9nOXuje3NkPEQSC3inkSzfsfi5zv//4lAx1jE2Ut0okG+5HWOMyUzY1U6WTtZGizz7SBrr+Ck+bAi9ieoKUEzSbaYd0CgYEAvGX5DFKrQ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6pkdr0yKochGkNf7+QW5MgwZCQIDAQAB';
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        $request = new \AlipaySystemOauthTokenRequest();
        $request->setGrantType("authorization_code");
        $request->setCode($code);
        $result = $aop->execute($request);
        $data = json_encode($result, 1);
        return json_decode($data, 1);
    }

    public function curl_get($url)
    {

        $header = array(
            'Accept: application/json',
        );
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 超时设置,以秒为单位
        curl_setopt($curl, CURLOPT_TIMEOUT, 1);
        // 超时设置，以毫秒为单位
        // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);
        // 设置请求头
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //执行命令
        $data = curl_exec($curl);

        // 显示错误信息
        if (curl_error($curl)) {
            print "Error: " . curl_error($curl);
        } else {
            // 打印返回的内容
            return $data;
            curl_close($curl);
        }
    }

    public function curl_post($url, $data = array())
    {

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        // POST数据

        curl_setopt($ch, CURLOPT_POST, 1);

        // 把post的变量加上

        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        $output = curl_exec($ch);

        curl_close($ch);

        return $output;

    }
}
